package com.sec.security;

import com.sec.dao.mysql.view.UserViewDao;
import com.sec.domain.mysql.view.UserView;
import org.springframework.beans.factory.annotation.Configurable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;

/**
 * 登陆验证时，通过username获取用户的所有权限信息，
 * 并返回User放到spring的全局缓存SecurityContextHolder中，以供授权器使用
 * Created by Administrator on 2017/10/31.
 */
@Configurable
public class MyUserDetailService implements UserDetailsService {

    @Resource
    private UserViewDao userViewDao;

    //登陆验证时，通过username获取用户的所有权限信息，
    //并返回User放到spring的全局缓存SecurityContextHolder中，以供授权器使用
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException, DataAccessException {
        Collection<GrantedAuthority> auths = new ArrayList<>();
        UserView userView = new UserView();
        userView.setUsername(username);
        List<UserView> userViewList = userViewDao.queryByCon(userView);
        if(userViewList!=null && userViewList.size()>0){
            for(UserView userView1 : userViewList){
                SimpleGrantedAuthority auth1 = new SimpleGrantedAuthority(userView1.getRoleName());
                auths.add(auth1);
            }
            Long salt = userViewList.get(0).getUserId(); // 设置salt为userId
            return new MyUser(username, userViewList.get(0).getPassword(), true, true, true, true, auths, salt);
        }
        return null;
    }
}
